/**
 *
 */
package com.ozq;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;

import org.mozilla.javascript.ErrorReporter;
import org.mozilla.javascript.EvaluatorException;

import com.googlecode.htmlcompressor.compressor.HtmlCompressor;
import com.yahoo.platform.yui.compressor.CssCompressor;
import com.yahoo.platform.yui.compressor.JavaScriptCompressor;

/**
 * <压缩js 和 css> <手动压缩>
 * 
 * @author 欧增奇
 * @version [版本号, 2016年6月4日]
 * @see [相关类/方法]
 * @since [产品/模块版本]
 */
public class YuiCompress
{
    public static void main(String[] args) throws IOException
    {
        // 待压缩目录
        String to_path = "C:\\Users\\ouzengqi\\Desktop\\OzqBlog";
        // 压缩后的目录
        String do_path = "C:\\Users\\ouzengqi\\Desktop\\ROOT";
        findDirectoryCompressor("", to_path, do_path);
    }

    /**
     * 寻找文件并压缩，注意1.参数分割用\\不用/ 2.不用\\或/结束
     * 
     * @param temp_path
     *            待处理的文件
     * @param to_path
     *            待压缩目录
     * @param do_path
     *            压缩后的目录
     * @throws IOException
     * @throws FileNotFoundException
     */
    private static void findDirectoryCompressor(String temp_path, String to_path, String do_path)
    {
        File file = new File(temp_path == null || temp_path.length() <= 0 ? to_path : temp_path);
        if (file.exists())
        {
            if (!file.isDirectory())
            {// 文件
                if (file.exists())
                {
                    String file_path = file.getPath();
                    String temp_handle_path = file_path.replace(to_path, "");
                    String temp_do_path = do_path + temp_handle_path;

                    System.out.println("----------start-----------");
                    System.out.println("开始处理：" + file_path);
                    if (file_path.endsWith(".js"))
                    {
                        System.out.println("处理方法：js");
                        if (!jsCompressor(file_path, temp_do_path))
                        {
                            System.out.println("处理结果：js失败，最终直接复制");
                            copy(file_path, temp_do_path);
                        }
                    } else if (file_path.endsWith(".css"))
                    {
                        System.out.println("处理方法：css");
                        if (!cssCompressor(file_path, temp_do_path))
                        {
                            System.out.println("处理结果：css失败，最终直接复制");
                            copy(file_path, temp_do_path);
                        }
                    } else if (file_path.endsWith(".html"))
                    {
                        System.out.println("处理方法：html");
                        if (!htmlCompressor(file_path, temp_do_path))
                        {
                            System.out.println("处理结果：html失败，最终直接复制");
                            copy(file_path, temp_do_path);
                        }
                    } else
                    {
                        System.out.println("处理方法：复制");
                        copy(file_path, temp_do_path);
                    }
                    System.out.println();
                }
            } else if (file.isDirectory())
            {// 文件夹
                File[] filelist = file.listFiles();
                for (File file2 : filelist)
                {
                    findDirectoryCompressor(file.getPath() + File.separator + file2.getName(), to_path, do_path);
                }
            }
        }
    }

    /**
     * 压缩js方法
     * 
     * @param to_path
     * @param do_path
     * @throws IOException
     * @throws FileNotFoundException
     */
    private static boolean jsCompressor(String to_path, String do_path)
    {
        try
        {
            mkDir(do_path);
            File file = new File(to_path);
            FileWriter writer = new FileWriter(new File(do_path));

            Reader in = new InputStreamReader(new FileInputStream(file));
            JavaScriptCompressor javaScriptCompressor = new JavaScriptCompressor(in, new ErrorReporter()
            {

                public void error(String message, String sourceName, int line, String lineSource, int lineOffset)
                {
                    /*
                     * if (line < 0) { System.err.println("/n[ERROR] " + message); } else { System.err.println("/n[ERROR] " + line + ':' + lineOffset + ':' + message); }
                     */
                }

                public EvaluatorException runtimeError(String message, String sourceName, int line, String lineSource, int lineOffset)
                {
                    error(message, sourceName, line, lineSource, lineOffset);
                    return new EvaluatorException(message);
                }

                public void warning(String message, String sourceName, int line, String lineSource, int lineOffset)
                {
                    /*
                     * if (line < 0) { System.err.println("/n[WARNING] " + message); } else { System.err.println("/n[WARNING] " + line + ':' + lineOffset + ':' + message); }
                     */
                }
            });
            javaScriptCompressor.compress(writer, -1, true, false, false, false);
            writer.flush();
            writer.close();
            return true;
        } catch (Exception e)
        {
            return false;
        }
    }

    /**
     * 压缩css方法
     * 
     * @param to_path
     * @param do_path
     * @throws IOException
     */
    private static boolean cssCompressor(String to_path, String do_path)
    {
        try
        {
            mkDir(do_path);
            File file = new File(to_path);
            FileWriter writer = new FileWriter(new File(do_path));
            Reader in = new InputStreamReader(new FileInputStream(file));

            CssCompressor cssCompressor = new CssCompressor(in);
            cssCompressor.compress(writer, -1);
            writer.flush();
            writer.close();
            return true;
        } catch (Exception e)
        {
            return false;
        }
    }

    /**
     * 压缩css方法
     * 
     * @param to_path
     * @param do_path
     * @throws IOException
     */
    @SuppressWarnings("resource")
    private static boolean htmlCompressor(String to_path, String do_path)
    {
        try
        {
            mkDir(do_path);
            File file = new File(to_path);
            FileWriter writer = new FileWriter(new File(do_path));
            Reader in = new InputStreamReader(new FileInputStream(file));

            String line;
            StringBuffer sb = new StringBuffer();
            BufferedReader br = new BufferedReader(in);
            while((line = br.readLine()) != null)
                sb.append(line);

            HtmlCompressor htmlCompressor = new HtmlCompressor();
            writer.write(htmlCompressor.compress(sb.toString()));
            writer.flush();
            writer.close();
            return true;
        } catch (Exception e)
        {
            return false;
        }
    }

    /**
     * 复制文件
     * 
     * @param to_path
     * @param do_path
     * @return
     */
    private static boolean copy(String to_path, String do_path)
    {
        try
        {
            mkDir(do_path);
            FileInputStream in = new FileInputStream(to_path);
            FileOutputStream out = new FileOutputStream(do_path);

            byte[] bt = new byte[1024];
            int count;
            while((count = in.read(bt)) > 0)
            {
                out.write(bt, 0, count);
            }
            in.close();
            out.close();
            return true;
        } catch (IOException ex)
        {
            return false;
        }
    }

    /**
     * 创建上层目录
     * 
     * @param do_path
     * @throws IOException
     */
    private static void mkDir(String do_path) throws IOException
    {
        File file = new File(do_path);
        File parent_file = new File(file.getParent());
        if (!parent_file.exists() && !parent_file.isDirectory())
        {
            parent_file.mkdirs();
        }
        if (!file.exists())
        {
            file.createNewFile();
        }
    }
}
